import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';

part 'at_user_model.g.dart';

@JsonSerializable()
class ATUserModel {
  int? type; //0-文本 1-@用户  2-表情
  String? text;
  String? userId;
  String? imId;
  String? url;
  int userStatus = 0;
  String? nickname;
  String? userRemark;

  ATUserModel();

  factory ATUserModel.fromJson(Map<String, dynamic> json) => _$ATUserModelFromJson(json);

  Map<String, dynamic> toJson() => _$ATUserModelToJson(this);
}

class EmojiTextAttachment extends WidgetSpan {
  final String emojiStr;

  EmojiTextAttachment({required this.emojiStr, required Widget child}) : super(child: child);
}

class ATTextAttachment extends WidgetSpan {
  final ATUserModel model;

  ATTextAttachment({required this.model, required Widget child}) : super(child: child);
}

// 判断字符是否为表情符号
bool isEmojiCharacter(String char) {
  final int codeUnit = char.runes.first;
  return (codeUnit >= 0x1F600 && codeUnit <= 0x1F64F) ||
      (codeUnit >= 0x1F300 && codeUnit <= 0x1F5FF) ||
      (codeUnit >= 0x1F680 && codeUnit <= 0x1F6FF) ||
      (codeUnit >= 0x2600 && codeUnit <= 0x26FF) ||
      (codeUnit >= 0x2700 && codeUnit <= 0x27BF);
}

// 解析字符串并转换为 ATUserModel 列表
List<ATUserModel> convertStringToATUserModels(String input, List<FriendModel> users) {
  // final regex = RegExp(r'(@\w+)|(\p{Emoji_Presentation})', unicode: true);
  final regex = RegExp(r'(@\S+)|(\p{Emoji_Presentation})', unicode: true);
  List<ATUserModel> result = [];

  input.splitMapJoin(
    regex,
    onMatch: (match) {
      int type = 0;
      if (match.group(1) != null) {
        type = 1; // @昵称
        var u = users.firstWhereOrNull((element) => "@${element.nickname}" == match.group(0));
        if (u != null) {
          result.add(
            ATUserModel()
              ..text = match.group(0)
              ..type = type
              ..imId = u.imId
              ..userId = u.userId.toString()
              ..userStatus = u.status ?? 0
              ..nickname = u.nickname
              ..userRemark = u.userRemark,
          );
        }
      } else if (match.group(2) != null) {
        type = 2; // Emoji
        result.add(ATUserModel()
          ..text = match.group(0)
          ..type = type);
      }

      return '';
    },
    onNonMatch: (text) {
      if (text.isNotEmpty) {
        result.add(ATUserModel()
          ..text = text
          ..type = 0); // 普通文本
      }
      return '';
    },
  );

  return result;
}
